// 示例demo
const plugin = requirePlugin('ppScale-plugin')
var app = getApp();
Page({
    data: {
        deviceslist:[],
        param: {
            appKey:"需要向开发者申请"
        }
    },

    onUnload() {
        // 业务结束后需要调用此方法
        plugin.Blue.stop()
    },
    // 选择设备
    selItem: function(res) {
        var that = this;
        var devItem = res.currentTarget.dataset.item;
        var device = this.data.deviceslist.find(item => item.deviceId === devItem.deviceId)
        app.globalData.selmac = device;
        console.log("this.globalData",app.globalData.selmac)
        that.setData({
            selmac: device
        })
    },
    refresh: function(res) {
        // plugin.Blue.startBluetoothDevicesDiscovery()
        plugin.Blue.start([])
    },
    doback: function(res) {
        if(app.globalData.selmac){
            wx.navigateTo({
                url: '/clockInPage/deviceMeasure/deviceMeasure'
            })
        }else {
            console.log('请选择设备')
        }
    },
    doback2: function(res) {
        if(app.globalData.selmac){
            wx.navigateTo({
                url: '/pages/devicedetailfood/index'
            })
        }else {
            console.log('请选择设备')
        }
    },

    /**
     * 刷新token
     * @param  {function} fn   获取token后执行函数
     * @param  {boolean}  flag 请求刷新token
     */
    async refreshToken(fn, flag) {
        let bodyToken = wx.getStorageSync('bodyToken');
        let bodyTokenTime = wx.getStorageSync('bodyTokenTime');
        if (!bodyToken || bodyTokenTime * 1000 < +new Date() || flag) {
            let res = await plugin.refreshToken({
                url: 'https://uniquehealth.lefuenergy.com',
                data: {
                    "appSecret":"需要向开发申请",
                    "appKey": "需要向开发者申请"
                }
            });
            console.log("res", res);
            if (res.data.code == 200) {
                wx.setStorageSync('bodyToken', res.data.data.token);
                wx.setStorageSync('bodyTokenTime', res.data.data.expireTime);
                fn();
            }
        } else {
            fn();
        }
    },
    getDeviceSettingList(param) {
        let bodyToken = wx.getStorageSync('bodyToken');
        console.log("param",param)
        plugin.getDeviceSettingList({
            url: 'https://uniquehealth.lefuenergy.com',
            data: param,
            header: {
                "token": bodyToken,
                "Accept-Language": wx.getStorageSync("lang") || 'zh'
            }
        }).then(this.handleResponse);
    },
    handleResponse(res) {
        if (res.data.code == 200) {
            // 配置蓝牙设备列表
            console.log("res.data.data",res.data.data)
            plugin.Blue.setDeviceSetting(res.data.data)
        } else if (res.data.code == 401) {
            // token过期 重新请求token解析数据
            this.refreshToken(() => {
                this.getDeviceSettingList(this.data.param)
            }, true);
        }
    },

    onShow() {
        // 高于1.0.5版本 如无法扫描设备 需请求获取并设置最新设备配置列表
        // this.getDeviceSettingList(this.data.param)
       setTimeout(() => {
         
      
            plugin.Blue.setDeviceSetting([ {advLength: 999,
                calorieStatus: 0,
                createBy: null,
                deviceAccuracyType: 2,
                deviceCalcuteType: 4,
                deviceConnectType: 2,
                deviceFuncType: 223,
                deviceName: "CF577",
                devicePowerType: 3,
                deviceProtocolType: 3,
                deviceType: 1,
                deviceUnitType: "0,1,11",
                id: 51,
                imgUrl: null,
                macAddressStart: 6,
                remark: null,
                sign: "FF",
                status: 0,
                uhStatus: 1,
                updateBy: null}])
        console.log("plugin.Blue",plugin)
        plugin.Blue.setDeviceSetting([{
          "id": 78,
          "deviceName": "CF597_G",
          "sign": "FF",
          "advLength": 19,
          "macAddressStart": 7,
          "deviceConnectType": 2,
          "deviceType": 1,
          "deviceProtocolType": 4,
          "deviceCalcuteType": 4,
          "devicePowerType": 3,
          "deviceAccuracyType": 2,
          "remark": null,
          "customDeviceName": "CF597_G",
          "deviceFuncType": "0, 1, 2, 3, 4, 6, 7",
          "deviceUnitType": "0, 1",
          "isInternal": 0,
          "uhStatus": null,
          "status": 0,
          "imgUrl": "https://unique.lefuenergy.com/prod/2023/11/23/Property%201%3D%E7%A7%A4%E5%9B%BE%E6%A0%87%2056%2C%20Property%202%3DCF597%28%E6%95%88%E6%9E%9C%E5%9B%BE%29%403x_20231123113545A002.png",
          "brandId": 1,
          "brand": {
            "brandName": "Unique Health",
            "brandLogo": "https://unique.lefuenergy.com/prod/2023/11/23/Property%201%3Dunique%403x_20231123185316A001.png"
          }
        }, ])
        plugin.Blue.start([],false)
        // 获取扫描设备列表
        plugin.bus.subscribe("devicesList", (res) => {
            // console.log("devicesList'", JSON.parse(JSON.stringify(res)))
            this.setData({
                deviceslist: res
            });
        });
      }, 300);
    },

})